package config

import (
	"fmt"
	"github.com/cihub/seelog"
	"github.com/olebedev/config"
	"kyland.com/eagle/lib/exception"
	"os"
	"strconv"
)

const (
	CONFIG_FILE = "etc/config.yml"
)

var (
	Config *config.Config
)

func LoadConfig() error {
	cfgTemp, err := config.ParseYamlFile(CONFIG_FILE)
	if err != nil {
		fmt.Fprintf(os.Stderr, "parse config from %s failed: %s", CONFIG_FILE, err)
		return err
	}

	mode := os.Getenv("MODE")
	if mode == "" {
		mode = "debug"
	}
	if Config, err = cfgTemp.Get(mode); err != nil {
		return err
	}
	return nil
}

func IsTest() bool {
	test, err := Config.Get("test")
	if err != nil {
		seelog.Errorf("get test config failed: %v", err)
		exception.Throw(err)
	}

	t := test.UString("is_test")
	isTest, err := strconv.ParseBool(t)
	if err != nil {
		seelog.Errorf("get test config failed: %v", err)
		exception.Throw(err)
	}
	return isTest
}

func InCluster() (bool, error) {
	k3sConfig, err := Config.Get("k3s")
	if err != nil {
		return false, fmt.Errorf("get k3s config failed: %v", err)
	}

	k3s := k3sConfig.UString("in_cluster")
	in, err := strconv.ParseBool(k3s)
	if err != nil {
		return false, fmt.Errorf("get k3s config failed: %v", err)
	}
	return in, nil
}

func GetTestNodeIP() string {
	test, err := Config.Get("test")
	if err != nil {
		seelog.Errorf("get test config failed: %v", err)
		exception.Throw(err)
	}

	return test.UString("test_node")
}
